import express from 'express';
import http from 'http';
import { WebSocketServer } from 'ws';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import { MCPClient } from './mcpClient.js';
import { AIProvider } from './aiProvider.js';
import cors from 'cors';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取配置
const config = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json'), 'utf8'));

// 初始化 MCP 客户端和 AI 提供者
const mcpClient = new MCPClient(config.mcp_servers, config.client_settings);
const aiProvider = new AIProvider(config.ai_models);

// 创建 Express 应用
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../dist')));

// 初始化状态
let isInitialized = false;
let tools = [];

// WebSocket 连接管理
const clients = new Set();

// WebSocket 连接处理
wss.on('connection', (socket) => {
  console.log('WebSocket 连接已建立');
  clients.add(socket);

  // 如果已初始化，立即发送初始化状态
  if (isInitialized) {
    socket.send(JSON.stringify({
      type: 'init_success',
      tools: tools
    }));
  }

  socket.on('message', async (message) => {
    try {
      const data = JSON.parse(message.toString());
      
      if (data.type === 'user_message') {
        // 处理用户消息
        const response = await aiProvider.chat([
          { role: 'user', content: data.content }
        ]);
        
        // 检查是否有工具调用
        if (response.tool_calls && response.tool_calls.length > 0) {
          // 通知前端开始工具调用
          socket.send(JSON.stringify({
            type: 'ai_thinking',
            content: response.content || ''
          }));
          
          // 发送每个工具调用信息
          for (const toolCall of response.tool_calls) {
            socket.send(JSON.stringify({
              type: 'tool_call',
              name: toolCall.function.name,
              arguments: toolCall.function.arguments
            }));
            
            // 执行工具调用
            const result = await mcpClient.callTool(
              toolCall.function.name,
              JSON.parse(toolCall.function.arguments)
            );
            
            // 发送工具结果
            socket.send(JSON.stringify({
              type: 'tool_result',
              name: toolCall.function.name,
              result: JSON.stringify(result, null, 2)
            }));
            
            // 更新消息历史
            response.message = [...(response.message || []), {
              role: 'tool',
              tool_call_id: toolCall.id,
              content: JSON.stringify(result)
            }];
          }
          
          // 获取最终回复
          const finalResponse = await aiProvider.chat([
            { role: 'user', content: data.content },
            ...(response.message || [])
          ]);
          
          // 发送最终回复
          socket.send(JSON.stringify({
            type: 'ai_response',
            content: finalResponse.content
          }));
        } else {
          // 直接发送 AI 回复
          socket.send(JSON.stringify({
            type: 'ai_response',
            content: response.content
          }));
        }
      }
      
      // 处理其他命令
      else if (data.type === 'command') {
        handleCommand(data.command, socket);
      }
    } catch (error) {
      console.error('处理消息错误:', error);
      socket.send(JSON.stringify({
        type: 'error',
        message: error.message
      }));
    }
  });

  socket.on('close', () => {
    console.log('WebSocket 连接已关闭');
    clients.delete(socket);
  });
});

// 处理命令
async function handleCommand(command, socket) {
  const [cmd, ...args] = command.slice(1).split(' ');
  
  switch (cmd) {
    case 'tools':
      const allTools = await mcpClient.getAllTools();
      socket.send(JSON.stringify({
        type: 'command_result',
        command: 'tools',
        data: allTools
      }));
      break;
      
    case 'servers':
      const servers = mcpClient.getServerStatus();
      socket.send(JSON.stringify({
        type: 'command_result',
        command: 'servers',
        data: servers
      }));
      break;
      
    case 'model':
      if (args[0]) {
        const success = aiProvider.switchModel(args[0]);
        socket.send(JSON.stringify({
          type: 'command_result',
          command: 'model',
          success,
          model: args[0]
        }));
      } else {
        const currentModel = aiProvider.getCurrentModel();
        socket.send(JSON.stringify({
          type: 'command_result',
          command: 'model',
          data: { currentModel }
        }));
      }
      break;
      
    default:
      socket.send(JSON.stringify({
        type: 'error',
        message: `未知命令: ${cmd}`
      }));
  }
}

// 提供配置接口
app.get('/api/config', (req, res) => {
  // 发送安全过滤后的配置（不包含 API 密钥等敏感信息）
  const safeConfig = {
    models: Object.keys(config.ai_models.configs),
    default_model: config.ai_models.default,
    server_count: config.mcp_servers.length
  };
  res.json(safeConfig);
});

// 所有路由都返回主页
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

// 初始化服务
async function initialize() {
  try {
    console.log('正在初始化 MCP 服务...');
    
    // 连接所有 MCP 服务器
    await mcpClient.connectAll();
    console.log('MCP 服务器连接成功');
    
    // 获取所有工具
    tools = await mcpClient.getAllTools();
    console.log(`已加载 ${tools.length} 个工具`);
    
    // 设置 AI 提供者的工具
    aiProvider.setTools(tools);
    
    isInitialized = true;
    console.log('初始化完成');
    
    // 向所有已连接的客户端广播初始化成功
    clients.forEach(client => {
      client.send(JSON.stringify({
        type: 'init_success',
        tools: tools
      }));
    });
    
  } catch (error) {
    console.error('初始化失败:', error);
    
    // 广播初始化失败
    clients.forEach(client => {
      client.send(JSON.stringify({
        type: 'init_error',
        message: error.message
      }));
    });
  }
}

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器正在运行: http://localhost:${PORT}`);
  initialize();
});

// 处理优雅关闭
process.on('SIGINT', async () => {
  console.log('正在关闭服务...');
  await mcpClient.disconnectAll();
  server.close(() => {
    console.log('服务已关闭');
    process.exit(0);
  });
});

process.on('SIGTERM', async () => {
  console.log('正在关闭服务...');
  await mcpClient.disconnectAll();
  server.close(() => {
    console.log('服务已关闭');
    process.exit(0);
  });
}); 